package net.jueb.object.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;


public class ObjectClient {
	
	public void Connect(String ip,int port)
	{
		NioEventLoopGroup group=new NioEventLoopGroup();
		Bootstrap bt=new Bootstrap();
		bt.group(group);
		bt.channel(NioSocketChannel.class);
		bt.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				
				/**
				 * Object编码解码器自带tcp分包拆包功能
				 */
				ObjectDecoder od=new ObjectDecoder(1024,ClassResolvers.cacheDisabled(this.getClass().getClassLoader()));
				sc.pipeline().addLast(od);
				sc.pipeline().addLast(new ObjectEncoder());
				sc.pipeline().addLast(new ObjectClientHandler());
			}
		});
		try {
			Channel channel=bt.connect(ip, port).sync().channel();
			channel.closeFuture().sync();//调用关闭等待
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}
	}
	public static void main(String[] args) {
		new ObjectClient().Connect("127.0.0.1", 7779);
	}
}
